package com.ruimayi.sitemoney.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.ruimayi.sitemoney.VolleyUtils.HttpCallBack;
import com.ruimayi.sitemoney.VolleyUtils.HttpUtil;
import com.ruimayi.sitemoney.adapter.AdapterShipin;
import com.ruimayi.sitemoney.app.MyApplication;
import com.ruimayi.sitemoney.beans.LoginModel;
import com.ruimayi.sitemoney.common.CommonParams;
import com.ruimayi.sitemoney.utils.ACache;
import com.ruimayi.sitemoney.utils.DeviceUtils;
import com.ruimayi.sitemoney.utils.MediaUtils;
import com.ruimayi.sitemoney.utils.SharedPreferencesUtil;
import com.ruimayi.sitemoney.utils.SystemExternalFileUtils;
import com.ruimayi.sitemoney.utils.SystemFileUtils;
import com.ruimayi.sitemoney.utils.ToastUtil;
import com.ruimayi.sitemoney.views.MyListView;
import com.ruimayi.sitemoneyapp.R;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;

import static com.ruimayi.sitemoney.utils.ACache.TIME_DAY;


/**
 * 登录页面
 */
public class LoginActivity extends BaseActivity {
    @BindView(R.id.et_username)
    public EditText et_username;
    @BindView(R.id.et_password)
    public EditText et_password;
    @BindView(R.id.btn_login_submit)
    public Button btn_login_submit;
    @BindView(R.id.login_progress)
    public ProgressBar login_progress;

    @BindView(R.id.checkBoxLogin)
    public CheckBox checkBoxLogin;

    private ACache mACache;//缓存对此那个

    private String strUserName =null;//用户名
    private String strUserPwd = null;//密码
    private int iSaveUserValidity =7;//


    //======================下载==================
    private AdapterShipin mAdapterShipin;
    @BindView(R.id.lv_shipin)
    public MyListView mShipinListView;
    private List<String> videoNetworkUrls = new ArrayList<String>();
    private int downLoadFileSize= 0;//需要下载的文件数量


    @Override
    public int getContentViewId() {
        return R.layout.activity_login;
    }

    @Override
    public void initActivityParams(Bundle savedInstanceState) {
        tv_head_title.setText("登录");
//        myLoginHandler  =new MyLoginHandler(this);
        btn_login_submit.setOnClickListener(
                new View.OnClickListener(){
                    @Override
                    public void onClick(View view) {
                        checkLoginValue();
                    }
                }
        );

        //初始化
        File pageFileDirs = SystemFileUtils.getAppDirectory(actContext);
        if(pageFileDirs!=null && pageFileDirs.exists()){
            File accountFile = new File(pageFileDirs, "ACache");
            if(accountFile!=null){
                mACache = ACache.get(accountFile);
            }
        }
        if(mACache==null){
            mACache = ACache.get(actContext);
        }
        getUserInfo();
        if(!TextUtils.isEmpty(strUserName) && !TextUtils.isEmpty(strUserPwd)){
            //执行自动登录
            et_username.setText(strUserName);
            et_password.setText(strUserPwd);
            checkLoginValue();
        }

        //初始化视频列表
        initShiPinAdapter();
        getVidesUrlParmas();
    }

    public void gotoMainActiviy(){
        Intent mIntent = new Intent();
        mIntent.setClass(LoginActivity.this,MainActivity.class);
        startActivity(mIntent);
        finish();
    }

    public String getValueById(EditText editText){
        return editText.getText().toString().trim();
    }
    public void checkViewValue(String value,String content){
        if(TextUtils.isEmpty(value)){
            hideLoginProgress();
            ToastUtil.showShort(actContext,content);
            return;
        }
    }
    public void showLoginProgress(){
        if(login_progress!=null && login_progress.getVisibility()!=View.VISIBLE){
            login_progress.setVisibility(View.VISIBLE);
        }
    }
    public void hideLoginProgress(){
        if(login_progress!=null && login_progress.getVisibility()!=View.GONE){
            login_progress.setVisibility(View.GONE);
        }
    }
    /**
     * 获取用户信息
     */
    public void getUserInfo(){
        if(mACache!=null){
            strUserName=  mACache.getAsString("user_name");
            strUserPwd = mACache.getAsString("user_pwd");
        }else{
            strUserName =null;
            strUserPwd = null;
        }
    }


    /**
     * 保存用户信息
     */
    public void saveUserInfo(){
        if(mACache!=null){
            mACache.put("user_name",strUserName,TIME_DAY*iSaveUserValidity);
            mACache.put("user_pwd",strUserPwd,TIME_DAY*iSaveUserValidity);
        }
    }
    /**
     * 保存用户的vpn
     */
    public void saveUserVpnParams(String vpnName,String vpnPwd){
        MyApplication.strVpnName = vpnName;
        MyApplication.strVpnPwd = vpnPwd;
        SharedPreferencesUtil.saveData(appContext,"user_vpn_name",vpnName);
        SharedPreferencesUtil.saveData(appContext,"user_vpn_pwd",vpnPwd);
    }

    /**
     * 检查登录信息
     */
    public void checkLoginValue(){
        showLoginProgress();
         strUserName = getValueById(et_username);
        checkViewValue(strUserName,"请输入用户名");
        strUserPwd = getValueById(et_password);
        checkViewValue(strUserPwd,"请输入用户名");

        HashMap<String,String> params = new HashMap<String,String>();
        params.put("deviceid", DeviceUtils.getImei(actContext));
        params.put("username",strUserName);
        params.put("password",strUserPwd);
        params.put("version",DeviceUtils.getVersionName(actContext));
        params.put("nettypename",DeviceUtils.getDeviceAc());
//
//        HashMap<String,String> weburl = new HashMap<String,String>();
//        weburl.put("web_url", CommonParams.URL_WEB_SITE_MONEY);
//        MyNetworkAsyncTask myNetworkAsyncTask = new MyNetworkAsyncTask(myLoginHandler);
//        myNetworkAsyncTask.execute(weburl,params);

        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_LOGIN, params, new HttpCallBack<LoginModel>() {
            @Override
            public void onSuccess(LoginModel loginModel) {
                hideLoginProgress();
                if(loginModel.getStatus()==2) {
                    //保存用户数据
                    if(checkBoxLogin.isChecked()){
                        iSaveUserValidity = loginModel.getDays();
                        saveUserInfo();
                        saveUserVpnParams(loginModel.getVpnname(),loginModel.getVpnpass());
                    }else{
                        mACache.clear();
                    }
                    //跳转到主页面
                    gotoMainActiviy();
                }else {
                    String strMsg = loginModel.getTip();
                    if(TextUtils.isEmpty(strMsg)){
                        strMsg = "登录失败";
                    }
                    showAlerDialog(strMsg);
                }
            }

            @Override
            public void onFail(String msg) {
                hideLoginProgress();
                showAlerDialog("登录失败");
            }
        });
    }

    /**
     * 初始化
     */
    public void initShiPinAdapter(){
        if(mAdapterShipin==null){
            mAdapterShipin = new AdapterShipin(actContext);
        }
        mShipinListView.setAdapter(mAdapterShipin);
        mShipinListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                String strUrl = videoNetworkUrls.get(position);
                if(!TextUtils.isEmpty(strUrl) && strUrl.startsWith("http")){
                    MediaUtils.playerNetUrl(actContext,strUrl.trim());
                }else if(!TextUtils.isEmpty(strUrl) && !strUrl.startsWith("http")){
                    MediaUtils.playeVideoLocalUrl(actContext,"file://"+strUrl.trim(),"video/*");
                }else{
                    ToastUtil.show(actContext,"视频地址错误", Toast.LENGTH_LONG);
                }

            }
        });
    }

    /**
     * 获取数据
     */
    public void getVidesUrlParmas(){
        showLoginProgress();
        if(videoNetworkUrls!=null){
            videoNetworkUrls.clear();
        }
        HashMap<String,String> params = new HashMap<String,String>();
        params.put("param","shipin");
        HttpUtil.getInstance().request_get(CommonParams.URL_WEB_SHIPIN, params, new HttpCallBack<String>() {
            @Override
            public void onSuccess(String datas) {
                if(!TextUtils.isEmpty(datas)){
                    Log.e("file_log","-------getVidesUrlParmas-------onSuccess---:"+datas);
                    datas = datas.replaceAll("\"","");
                    String[] strUrls = datas.split("\\,");
                    if(strUrls!=null && strUrls.length>0){
                        downLoadFileSize = strUrls.length;
                        for (String msg:strUrls ) {
                            videoNetworkUrls.add(msg);
                        }
                    }
                    //检查信息
                    checkShouZhuanVideos();
                }
            }

            @Override
            public void onFail(String msg) {
                Log.e("file_log","-------getVidesUrlParmas------onFail----:"+msg);
                downLoadFileSize =0;
                if(videoNetworkUrls!=null){
                    videoNetworkUrls.clear();
                }
                checkShouZhuanVideos();
            }
        });
    }
    /**
     * 检查教程视频信息
     */
    public void checkShouZhuanVideos(){
        //核对并创建文件夹
        hideLoginProgress();
        String strDirs =  SystemExternalFileUtils.createDirByExternal("",CommonParams.DownLoadFileParams.FILE_DOWNLOAD_DIRS);
        List<String > filesPath = null;//文件夹下所有文件
        if(!TextUtils.isEmpty(strDirs)){
            //文件夹不为空
            filesPath = SystemExternalFileUtils.getParentFiles(strDirs);
        }
        if(downLoadFileSize>0 && filesPath.size()!=downLoadFileSize){
            //需要下载视频教程
            mAdapterShipin.setDatas(videoNetworkUrls);
            mShipinListView.setVisibility(View.VISIBLE);
        }else if(filesPath.size()>0){
            //展示视频地址列表
            videoNetworkUrls.clear();
            videoNetworkUrls.addAll(filesPath);
            mAdapterShipin.setDatas(videoNetworkUrls);
            mShipinListView.setVisibility(View.VISIBLE);
        }else{
            mShipinListView.setVisibility(View.GONE);
        }
    }
}
